package Util;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@WebFilter("/api/*")
public class AuthFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化方法，可获取过滤器配置参数
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {
        // 转换为 HTTP 特定的请求/响应对象
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        // 获取当前会话（如果不存在则不创建）
        HttpSession session = request.getSession(false);

        // 检查用户是否已登录
        if (session == null || session.getAttribute("user") == null) {
            // 未登录，转发到登录页
            req.getRequestDispatcher("/Pages/login.jsp").forward(req, res);
            return; // 终止过滤器链的执行
        }
        // 已登录，继续请求处理链
        chain.doFilter(req, res);
    }

    @Override
    public void destroy() {
        // 过滤器销毁时的清理工作
    }
}
